package com.hmjk.health.background.data;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.text.format.Time;
import android.util.Log;

import com.hmjk.health.HealthApp;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.background.DatabaseHelper;
import com.hmjk.health.background.NetService;

public class DeviceListUpdated extends DataUpdated{
	private static String TAG = DeviceListUpdated.class.getSimpleName();
	
	private void logd(String info){
		Log.d(TAG, info);
	}
	
	public DeviceListUpdated(HealthApp app, DataManager dm) {
		super(app, dm);
		UPDATE_TIME = 60 * 60 * 1000;
	}
	
	@Override
	public void setUserData(Object data) {
		reqTime = 0;
	}

	@Override
	public long delay() {
		long curMs = System.currentTimeMillis();
		long del = curMs - upTime;
		logd("delay curMs="+curMs+" upTime="+upTime+" del="+del);
		if(del >= UPDATE_TIME){
			logd("delay 0");
			return 0;
		}else{
			logd("delay (UPDATE_TIME - del) = "+(UPDATE_TIME - del));
			return (UPDATE_TIME - del);
		}
	}

	private void doRequest(String uid){		
		Intent si = new Intent(NetService.GET_DATA_ACTION);
		si.putExtra("sub_act", NetService.GET_DEVICE_LIST);
		si.putExtra("uid", uid);
		Time t = new Time();
		t.setToNow();
		String stamp = "GET_DEVICE_LIST" + t.toString(); 
		si.putExtra("stamp",stamp);
		mApp.addNetHandler(stamp,mDm.getBackGroundHandler());
		mApp.startService(si);
	}
	
	@Override
	public boolean grab() {
		String uid = mApp.getUID();
		logd("grab uid="+uid);
		if(uid == null)
			return false;
		
		long curMs = System.currentTimeMillis();
		logd("grab curMs="+curMs+" reqTime="+reqTime);
		if((curMs - reqTime) > UPDATE_TIME){
			doRequest(uid);
			reqTime = curMs;
			logd("grab req sent!");
			return true;
		}
		return false;
	}

	@Override
	public boolean grabByUser() {
		String uid = mApp.getUID();
		logd("grabByUser uid="+uid);
		if(uid == null)
			return false;
		
		long curMs = System.currentTimeMillis();
		logd("grabByUser curMs="+curMs+" reqTime="+reqTime);
		if((curMs - reqTime) > MIN_QUERY_DUR * 1000){
			doRequest(uid);
			reqTime = curMs;
			logd("grabByUser req sent!");
			return true;
		}
		return false;
	}

	@Override
	public void receive(String stamp, String sjson) {
		DatabaseHelper dh = mDm.getDatabaseHelper();
		if(dh == null)
			return;
		
		if(stamp.startsWith("GET_DEVICE_LIST")){
		if(sjson != null){
			boolean update = false;
			try {
				JSONObject json = new JSONObject(sjson);
				int code = json.getInt("code");
				if(code == 200){
					String state = json.getString("state");
					if(state.equalsIgnoreCase("00")){
						JSONObject recdata = json.getJSONObject("recdata");
						if(recdata != null){
							JSONArray array = null;
							dh.clearDevlistTable();
							upTime = System.currentTimeMillis();
							
							if(recdata.has("devicearray")){
								array = recdata.getJSONArray("devicearray");
							}
							if((array != null) && (array.length() > 0)){
								for(int index = 0; index < array.length(); index ++){
									JSONObject o = array.getJSONObject(index);
									ContentValues cv = new ContentValues();
									String tid = o.getString("tid");
									cv.put(DatabaseHelper.DEVLIST_TID, tid);
									//String fid = o.getString("fid");
									cv.put(DatabaseHelper.DEVLIST_FID, "");
									
									String name = "";
									if(o.has("devicename")){
										name = o.getString("devicename");
									}
									cv.put(DatabaseHelper.DEVLIST_NAME, name);
									
									String type = "";
									if(o.has("devicetype")){
										type = o.getString("devicetype");
									}
									cv.put(DatabaseHelper.DEVLIST_TYPE, type);
									
									String admin = "0";
									if(o.has("admin")){
										admin = o.getString("admin");
										if(!admin.equals("0") && !admin.equals("1") && !admin.equals("2")){
											admin = "0";
										}
									}
									cv.put(DatabaseHelper.DEVLIST_ADMIN, admin);
									
									String status = "1";
									if(o.has("devicestate")){
										status = o.getString("devicestate");
										if(!status.equals("0") && !status.equals("1") && !status.equals("2")){
											status = "1";
										}
									}
									cv.put(DatabaseHelper.DEVLIST_STATUS, status);
									
									cv.put(DatabaseHelper.DEVLIST_TIME, upTime);
									dh.addOneItem2DevlistTable(cv);
								}
							}
							dh.closeDB();
							update = true;
							
							DataUpdated mNotifer = getNotifier(DataManager.F_DEVICEFACE);
							if(mNotifer != null)
								mNotifer.setUserData(null); //DeviceFaceUpdated
							
							mNotifer = getNotifier(DataManager.F_MEASURE_REMINDER);	
							if(mNotifer != null)
								mNotifer.setUserData(null);
							
							mNotifer = getNotifier(DataManager.F_DRUG_REMINDER);	
							if(mNotifer != null)
								mNotifer.setUserData(null);
							
							mNotifer = getNotifier(DataManager.F_DEVICESUBLIST);	
							if(mNotifer != null)
								mNotifer.setUserData(null);
							
							mNotifer = getNotifier(DataManager.F_GLYCOSE_SET);	
							if(mNotifer != null)
								mNotifer.setUserData(null);
						}
					}
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			Intent i = new Intent(DataManager.DATA_UPDATE_ACTION);
			i.putExtra("type",DataManager.F_DEVICELIST);
			i.putExtra("state", update);
			mApp.sendBroadcast(i);
		}
		}else if(stamp.startsWith("COMMIT_DEVICE_NAME")){
			if(sjson != null){
				String state = "af";
				int code = 400;
				String tid = "";
				try {
					JSONObject json = new JSONObject(sjson);
					code = json.getInt("code");
					JSONObject sd = json.getJSONObject("senddata");
					tid = sd.getString("tid");
					String name = sd.getString("devicename");
					if(code == 200){
						state = json.getString("state");
						if(state.equalsIgnoreCase("00")){
							ContentValues cv = new ContentValues();
							Cursor c = dh.queryFromDevlistTable(tid);
							if(c.getCount() > 0){
								c.moveToNext();
								tid = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_TID));
								cv.put(DatabaseHelper.DEVLIST_TID, tid);
								String fid = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_FID));
								cv.put(DatabaseHelper.DEVLIST_FID, fid);
								cv.put(DatabaseHelper.DEVLIST_NAME, name);
								String type = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_TYPE));
								cv.put(DatabaseHelper.DEVLIST_TYPE, type);
								String admin = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_ADMIN));
								cv.put(DatabaseHelper.DEVLIST_ADMIN, admin);
								String status = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_STATUS));
								cv.put(DatabaseHelper.DEVLIST_STATUS, status);
							
								upTime = c.getLong(c.getColumnIndex(DatabaseHelper.DEVLIST_TIME));
								cv.put(DatabaseHelper.DEVLIST_TIME, upTime);
							}
							c.close();
							dh.updateOneInDevlistTable(tid,cv);
							dh.closeDB();
						}
					}
					
				}catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
				Intent i = new Intent(DataManager.DATA_COMMIT_RESULT);
				i.putExtra("type",DataManager.F_DEVICELIST);
				i.putExtra("state", state);
				i.putExtra("cmd", "COMMIT_DEVICE_NAME");
				i.putExtra("tid", tid);
				i.putExtra("code", code);
				mApp.sendBroadcast(i);
			}
		}else if(stamp.startsWith("COMMIT_DEVICE_ADMIN_ABORT") || stamp.startsWith("COMMIT_DEVICE_ADMIN_APPLY")){
			if(sjson != null){
				String state = "af";
				int code = 400;
				String tid = "";
				try {
					JSONObject json = new JSONObject(sjson);
					code = json.getInt("code");
					JSONObject sd = json.getJSONObject("senddata");
					tid = sd.getString("tid");
					if(code == 200){
						state = json.getString("state");
						if(state.equalsIgnoreCase("00")){
							ContentValues cv = new ContentValues();
							Cursor c = dh.queryFromDevlistTable(tid);
							if(c.getCount() > 0){
								c.moveToNext();
								tid = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_TID));
								cv.put(DatabaseHelper.DEVLIST_TID, tid);
								String fid = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_FID));
								cv.put(DatabaseHelper.DEVLIST_FID, fid);
								String name = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_NAME));
								cv.put(DatabaseHelper.DEVLIST_NAME, name);
								String type = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_TYPE));
								cv.put(DatabaseHelper.DEVLIST_TYPE, type);
								
								if(stamp.startsWith("COMMIT_DEVICE_ADMIN_APPLY"))
									cv.put(DatabaseHelper.DEVLIST_ADMIN, "1");
								else
									cv.put(DatabaseHelper.DEVLIST_ADMIN, "0");
								
								String status = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_STATUS));
								cv.put(DatabaseHelper.DEVLIST_STATUS, status);
								
								upTime = c.getLong(c.getColumnIndex(DatabaseHelper.DEVLIST_TIME));
								cv.put(DatabaseHelper.DEVLIST_TIME, upTime);
							}
							c.close();
							dh.updateOneInDevlistTable(tid,cv);
							dh.closeDB();
						}
					}
					
				}catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
				Intent i = new Intent(DataManager.DATA_COMMIT_RESULT);
				i.putExtra("type",DataManager.F_DEVICELIST);
				i.putExtra("state", state);
				if(stamp.startsWith("COMMIT_DEVICE_ADMIN_APPLY"))
					i.putExtra("cmd", "COMMIT_DEVICE_ADMIN_APPLY");
				else
					i.putExtra("cmd", "COMMIT_DEVICE_ADMIN_ABORT");
				i.putExtra("tid", tid);
				i.putExtra("code", code);
				mApp.sendBroadcast(i);
			}
		}else if(stamp.startsWith("COMMIT_DEVICE_INTEREST_ABORT")){
			if(sjson != null){
				String state = "af";
				int code = 400;
				String tid = "";
				try {
					JSONObject json = new JSONObject(sjson);
					code = json.getInt("code");
					JSONObject sd = json.getJSONObject("senddata");
					tid = sd.getString("tid");
					if(code == 200){
						state = json.getString("state");
						if(state.equalsIgnoreCase("00")){
							dh.deleteOneInDevlistTable(tid);
							dh.closeDB();
						}
					}
					
				}catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
				
				if(state.equalsIgnoreCase("00")){
					DataUpdated mNotifer = getNotifier(DataManager.F_DEVICESUBLIST);	
					if(mNotifer != null)
						mNotifer.setUserData(null);
				}
				
				Intent i = new Intent(DataManager.DATA_COMMIT_RESULT);
				i.putExtra("type",DataManager.F_DEVICELIST);
				i.putExtra("state", state);
				i.putExtra("cmd", "COMMIT_DEVICE_INTEREST_ABORT");
				i.putExtra("tid", tid);
				i.putExtra("code", code);
				mApp.sendBroadcast(i);
			}
		}
	}

	@Override
	public Object check(String[] arg) {
		JSONObject ret = null;
		DatabaseHelper dh = mDm.getDatabaseHelper();
		if(dh == null)
			return null;
		
		if(arg == null){
			//return all
			Cursor c = dh.queryDevlistTableData();
			try {
				ret = new JSONObject();
				if(c.getCount() > 0){
					JSONArray array = new JSONArray();
					while(c.moveToNext()){
						String tid = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_TID));
						String fid = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_FID));
						String name = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_NAME));
						String status = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_STATUS));
						String type = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_TYPE));
						String admin = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_ADMIN));
					
						upTime = c.getLong(c.getColumnIndex(DatabaseHelper.DEVLIST_TIME));
						JSONObject e = new JSONObject();
						e.put("tid", tid);
						e.put("fid", fid);
						e.put("name", name);
						e.put("status", status);
						e.put("type", type);
						e.put("admin", admin);
						array.put(e);
					}
					ret.put("array", array);
					ret.put("uptime", upTime);
				}else{
					JSONArray array = new JSONArray();
					ret.put("array", array);
					ret.put("uptime", upTime);
				}
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				ret = null;
			}
			c.close();
			dh.closeDB();
		}else if((arg.length == 2) && (arg[0].length() > 0) && (arg[1].length() > 0)){
			if(arg[0].equalsIgnoreCase("DEV_SINGLE_TYPE")){
			//check type
			String checkType = arg[1];//single type
			Cursor c = dh.queryDevlistTableData();
			try {
				ret = new JSONObject();
				if(c.getCount() > 0){
					JSONArray array = new JSONArray();
					while(c.moveToNext()){
						String type = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_TYPE));
						if(type.contains(checkType)){
						String tid = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_TID));
						String fid = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_FID));
						String name = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_NAME));
						String status = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_STATUS));
						
						String admin = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_ADMIN));

						upTime = c.getLong(c.getColumnIndex(DatabaseHelper.DEVLIST_TIME));
						JSONObject e = new JSONObject();
						e.put("tid", tid);
						e.put("fid", fid);
						e.put("name", name);
						e.put("status", status);
						e.put("type", type);
						e.put("admin", admin);
						array.put(e);
						}
					}
					ret.put("array", array);
					ret.put("uptime", upTime);
				}else{
					JSONArray array = new JSONArray();
					ret.put("array", array);
					ret.put("uptime", upTime);
				}
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				ret = null;
			}
			c.close();
			dh.closeDB();
			}else if(arg[0].equalsIgnoreCase("DEV_TID")){
				//tid
				Cursor c = dh.queryFromDevlistTable(arg[1]);
				try {
					ret = new JSONObject();
					if(c.getCount() > 0){
						JSONArray array = new JSONArray();
						c.moveToNext();
						String tid = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_TID));
						String fid = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_FID));
						String name = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_NAME));
						String status = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_STATUS));
						String type = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_TYPE));
						String admin = c.getString(c.getColumnIndex(DatabaseHelper.DEVLIST_ADMIN));
						
						upTime = c.getLong(c.getColumnIndex(DatabaseHelper.DEVLIST_TIME));
						JSONObject e = new JSONObject();
						e.put("tid", tid);
						e.put("fid", fid);
						e.put("name", name);
						e.put("status", status);
						e.put("type", type);
						e.put("admin", admin);
						
						array.put(e);
						ret.put("array", array);
						ret.put("uptime", upTime);
					}else{
						JSONArray array = new JSONArray();
						ret.put("array", array);
						ret.put("uptime", upTime);
					}
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					ret = null;
				}
				c.close();
				dh.closeDB();
			}
		}
		
		return ret;
	}
	
	@Override
	public boolean commit(Object data) {
		String uid = mApp.getUID();
		
		if((uid == null) || uid.isEmpty())
			return false;
			
		JSONObject json = (JSONObject)data;
		if(json == null)
			return false;
		
		try {
			String cmd = json.getString("cmd");
			String tid = json.getString("tid");
			if(cmd.equalsIgnoreCase("updatename")){
				String devicename = json.getString("devicename");
				
				Intent si = new Intent(NetService.COMMIT_DATA_ACTION);
				si.putExtra("sub_act", NetService.COMMIT_DEVICE_NAME);
				si.putExtra("uid", uid);
				si.putExtra("tid", tid);
				si.putExtra("devicename", devicename);
				
				Time t = new Time();
				t.setToNow();
				String stamp = "COMMIT_DEVICE_NAME" + t.toString(); 
				si.putExtra("stamp",stamp);
				mApp.addNetHandler(stamp,mDm.getBackGroundHandler());
				mApp.startService(si);
				
				return true;
			}else if(cmd.equalsIgnoreCase("abortadmin")){
				Intent si = new Intent(NetService.COMMIT_DATA_ACTION);
				si.putExtra("sub_act", NetService.COMMIT_DEVICE_ADMIN_ABORT);
				si.putExtra("uid", uid);
				si.putExtra("tid", tid);
				
				Time t = new Time();
				t.setToNow();
				String stamp = "COMMIT_DEVICE_ADMIN_ABORT" + t.toString(); 
				si.putExtra("stamp",stamp);
				mApp.addNetHandler(stamp,mDm.getBackGroundHandler());
				mApp.startService(si);
				
				return true;
			}else if(cmd.equalsIgnoreCase("bindadmin")){		
				Intent si = new Intent(NetService.COMMIT_DATA_ACTION);
				si.putExtra("sub_act", NetService.COMMIT_DEVICE_ADMIN_APPLY);
				si.putExtra("uid", uid);
				si.putExtra("tid", tid);
				
				String devicename = json.getString("devicename");
				si.putExtra("devicename", devicename);
				
				Time t = new Time();
				t.setToNow();
				String stamp = "COMMIT_DEVICE_ADMIN_APPLY" + t.toString(); 
				si.putExtra("stamp",stamp);
				mApp.addNetHandler(stamp,mDm.getBackGroundHandler());
				mApp.startService(si);
				
				return true;
			}else if(cmd.equalsIgnoreCase("abortinterest")){
				Intent si = new Intent(NetService.COMMIT_DATA_ACTION);
				si.putExtra("sub_act", NetService.COMMIT_DEVICE_INTEREST_ABORT);
				si.putExtra("uid", uid);
				si.putExtra("tid", tid);
				
				Time t = new Time();
				t.setToNow();
				String stamp = "COMMIT_DEVICE_INTEREST_ABORT" + t.toString(); 
				si.putExtra("stamp",stamp);
				mApp.addNetHandler(stamp,mDm.getBackGroundHandler());
				mApp.startService(si);
				
				return true;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return false;
	}

	@Override
	public void release() {
		// TODO Auto-generated method stub
		
	}
}
